<?php
/**
 * 模板替换中需要用到的函数
 * @copyright            copyright(c) 2011 - 2012 极好居
 * @author                anqiu xiao
 * @contact                QQ:89249294 E-mail:jihaoju@qq.com
 * @date                Sun May 13 14:35:08 CST 2012
 */
function tpc_transamp($template)
{
    $template = str_replace('&', '&amp;', $template);
    $template = str_replace('&amp;amp;', '&amp;', $template);
    $template = str_replace('\"', '"', $template);
    return $template;
}

function tpc_stripvtags($expr, $statement = '')
{
    $expr = preg_replace_callback("/\<\?\=(\\\$.+?)\?\>/s", function ($r) {
        return $r[1];
    }, $expr);
    $expr = str_replace("\\\"", "\"", $expr);
    $statement = str_replace("\\\"", "\"", $statement);
    return $expr . $statement;
}

function tpc_addquote($var)
{
    return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function tpc_stripscriptamp($s)
{
    $s = str_replace('&amp;', '&', $s);
    return "<script src=\"$s\" type=\"text/javascript\"></script>";
}

function tpc_stripblock($var, $s)
{
    $s = str_replace('\\"', '"', $s);
    $s = preg_replace("/<\?=\\\$(.+?)\?>/", "{\$\\1}", $s);
    preg_match_all("/<\?=(.+?)\?>/e", $s, $constary);
    $constadd = '';
    $constary[1] = array_unique($constary[1]);
    foreach ($constary[1] as $const) {
        $constadd .= '$__' . $const . ' = ' . $const . ';';
    }
    $s = preg_replace("/<\?=(.+?)\?>/", "{\$__\\1}", $s);
    $s = str_replace('?>', "\n\$$var .= <<<EOF\n", $s);
    $s = str_replace('<?', "\nEOF;\n", $s);
    return "<?\n$constadd\$$var = <<<EOF\n" . $s . "\nEOF;\n?>";
}

function tpc_getblock($matches)
{
    $id = $matches[2];
    $file = TpcTemplate::getInstance()->_getBlockFile($id);
    if (!is_file($file)) {
        create_block_tpl($id);
    }
    $tpl_content = file_get_contents($file);
    return "\r\n" . TpcTemplate::getInstance()->build($tpl_content) . "\r\n";
}

function tpc_subtpl($matches)
{
    $id = $matches[2];
    $options = TpcTemplate::getInstance()->getOptions();
    $file = TpcTemplate::getInstance()->_getTplFile($id);
    $tpl_content = file_get_contents($file . $options['suffix']);
    return "\r\n" . TpcTemplate::getInstance()->build($tpl_content) . "\r\n";
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access public
 * @param mix $value
 *
 * @return mix
 */
function tpc_addslashes_deep($value)
{
    if (empty($value)) {
        return $value;
    } else {
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes(trim($value));
    }
}

// 循环创建目录
if (!function_exists('dmkdir')) {
    function dmkdir($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return true;
        if (!dmkdir(dirname($dir), $mode)) return false;
        return @mkdir($dir, $mode);
    }
}